package indi.zhifa.engine.starter.mpenhance;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import indi.zhifa.engine.mpenhance.handler.BaseMetaObjectHandlerAdapter;
import indi.zhifa.engine.mpenhance.handler.SqlExceptionHandle;
import indi.zhifa.engine.mpenhance.properties.MetaObjectHandlerProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.sql.DataSource;

@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "zhifa.mp-enhance",name = "enabled", havingValue = "true")
public class MpEnhanceAutoConfig {

    @ConfigurationProperties(prefix = "zhifa.mp-enhance.meta-object.properties")
    @Bean
    public MetaObjectHandlerProperty metaObjectHandlerProperty(){
        return new MetaObjectHandlerProperty();
    }

    @ConditionalOnProperty(prefix = "zhifa.mp-enhance.meta-object.default",name = "enabled", havingValue = "true")
    @Bean
    public BaseMetaObjectHandlerAdapter baseMetaObjectHandlerAdapter(MetaObjectHandlerProperty pMetaObjectHandlerProperty){
        return new BaseMetaObjectHandlerAdapter(pMetaObjectHandlerProperty);
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 分页
        PaginationInnerInterceptor mysqlInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        interceptor.addInnerInterceptor(mysqlInnerInterceptor);

        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return interceptor;
    }

    @Bean
    public SqlExceptionHandle sqlExceptionHandle(){
        return new SqlExceptionHandle();
    }

}
